<template>
  <div class="base-group" :class="classes">
    <div class="base-group-item" v-for="(item,index) in value" :key="item.key || index">
      <slot v-if="simpleLayout && index < maxItem" v-bind="{item:item,index:index}"></slot>
      <div v-else-if="index < maxItem" class="base-group-content">
        <slot v-bind="{item:item,index:index}"></slot>
        <el-button icon="close" class="btn-icon base-group-remove" v-if="value.length>1" @click="handleRemove(index)" :disabled="disabled"></el-button>
      </div>
      <template v-if="simpleLayout">
        <el-button icon="plus" class="btn-icon" v-if="index===value.length - 1" @click="handleAdd(index)" :disabled="maxItem <= value.length || disabled"></el-button>
        <el-button icon="minus" class="btn-icon" v-if="simpleLayout && index!==value.length - 1" @click="handleRemove(index)" :disabled="item.disabled || disabled"></el-button>
      </template>
      <div class="tr" v-else>
        <el-button icon="plus" class="btn-icon" v-if="index===value.length - 1 && maxItem > 1" @click="handleAdd(index)" :disabled="maxItem <= value.length || disabled"></el-button>
      </div>
    </div>
  </div>
</template>
<script>
  export default {
    props: {
      value: {
        type: [Array],
        default () {
          return []
        }
      },
      maxItem: { // 最大项目数
        type: Number,
        default: 100
      },
      disabled: {
        type: Boolean,
        default: false
      },
      simpleLayout: {
        type: Boolean,
        default: true
      }
    },
    computed: {
      classes () {
        return { 'base-group-simple': this.simpleLayout }
      }
    },
    methods: {
      handleAdd (index) {
        this.$emit('add', index)
        this.$nextTick(() => { // 被添加的表单控件得到焦点
          let node = this.$el.querySelector('.base-group-item:last-child input')
          node && node.focus()
        })
      },
      handleRemove (index) {
        this.$emit('remove', index)
      }
    }
  }
</script>

<style lang="scss">
    @import '~styles/var.scss';
    .base-group {
      &-item+&-item {
          margin-top: 15px;
      }
      .btn-icon{
        margin:10px 0;
      }
      &-simple{
        .btn-icon{
          margin: 0 10px;
        }
      }
      &-content{
        border:1px dashed #ddd;
        padding: 15px;
        position:relative;
      }
      &-remove{
        position:absolute;
        right:0;
        top:0;
        border:0;
        margin:0!important;
        padding:5px!important;
        i{
          transform: scale(0.8)
        }
      }
    }
</style>
